import { start as startAdmin } from "maishu-chitu-admin";
import "./database";
import { getClientComponentInfos, MyServerContext, Settings, settings as commonSettings } from "./common";
import path = require("path");
import { permissions, stationPath, ServerContextData } from "./website-config";
import { errors } from "./errors";
import { createDatabaseIfNotExists } from "maishu-node-auth";

export { Settings } from "./common";
export { menuItemIds } from "./website-config";
export async function start(settings: Settings) {

    if (!settings) throw errors.argumentNull("settings");
    Object.assign(commonSettings, settings);

    await createDatabaseIfNotExists(settings.db);

    let sourcePath = path.join(__dirname, "./");
    let componentInfos = getClientComponentInfos(sourcePath);
    let serverContextData: ServerContextData = { gateway: settings.gateway };

    startAdmin({
        port: settings.port,
        rootDirectory: __dirname,
        virtualPaths: Object.assign(settings.virtualPaths || {}, {
            "mobile/json.js": path.join(__dirname, 'static/lib/requirejs-plugins/src/json.js'),
            "mobile/text.js": path.join(__dirname, 'static/lib/requirejs-plugins/lib/text.js'),
            // "mobile/less.js": path.join(__dirname, 'static/lib/require-less-0.1.5/less.js'),
            // "mobile/lessc.js": path.join(__dirname, 'static/lib/require-less-0.1.5/lessc.js'),
            // "mobile/normalize.js": path.join(__dirname, 'static/lib/require-less-0.1.5/normalize.js')
        }),
        sourceDirectory: sourcePath,
        proxy: {
            "^/Images/Editor/(\\S+)": "http://web.alinq.cn/store2/Images/Editor/$1"
        },
        actionFilters: [
            (req, res, context: MyServerContext) => {
                context.componentInfos = componentInfos;
                return null;
            }
        ],
        station: {
            gateway: settings.gateway,
            path: stationPath,
            permissions
        },
        logLevel: "all",
        serverContextData,
    })
}
